﻿using GN.Pay.Utils;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Security;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Linq;

namespace GN.Pay.TradeChannel.WeiXin
{
    /// <summary>
    /// 处理微信支付公共类方法
    /// </summary>
    public static class WeiXinUtils
    {
        /// <summary>
        /// 转为Xml字典
        /// </summary>
        /// <param name="xml">xml</param>
        /// <returns></returns>
        public static SignDictionary ToXmlDictionary(string xml)
        {
            try
            {
                XmlDocument doc = new XmlDocument();
                doc.LoadXml(xml);
                var dic = new SignDictionary();
                var root = doc.DocumentElement;
                foreach (XmlNode node in root.ChildNodes)
                {
                    if (!string.IsNullOrWhiteSpace(node.Name))
                    {
                        dic[node.Name] = node.InnerText;
                    }
                }
                return dic;
            }
            catch
            {
                throw new FormatException("Xml 格式不正确");
            }
        }


        /// <summary>
        ///构建微信参数为XML格式
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public static string ParseXML(IDictionary<string, string> param)
        {
            if (param == null)
            {
                return "";
            }
            StringBuilder builder = new StringBuilder();
            List<string> list = param.Keys.ToList();
            list.Sort();
            builder.Append("<xml>");
            foreach (string str in list)
            {
                string input = param[str];
                var key = str.ToLowerInvariant();
                if (!string.IsNullOrWhiteSpace(key) && !string.IsNullOrWhiteSpace(input))
                {
                    if (!input.Equals("detail"))
                    {
                        builder.Append("<" + key + ">" + input + "</" + key + ">");
                    }
                    else
                    {
                        builder.Append("<" + key + "><![CDATA[" + input + "]]></" + key + ">");
                    }
                }
            }
            builder.Append("</xml>");
            return builder.ToString();
        }
                
    }
}
